//
//  CNGasInputController.m
//  CarNote
//
//  Created by linshili on 13-10-7.
//  Copyright (c) 2013年 linshili. All rights reserved.
//

#import "CNGasInputController.h"
#import "CNKeyBoardTopBar.h"
#import "CNGasMoneyCaculator.h"
#import "CNGasDataManager.h"
#import "CNGlobal.h"

//cell IDs of the cells in tableview
#define kCreateTimestampCellID @"kCreateTimestampCellID"
#define kOdometerCellID @"kOdometerCellID"
#define kPriceCellID @"kPriceCellID"
#define kFillGasCellID @"kFillGasCellID"
#define kTotalPayCellID @"kTotalPayCellID"
#define kIsFillUpCellID @"kIsFillUpCellID"
#define kDatePickerCellID @"kDatePickerCellID"

#define DatePickerHeight 160


@interface CNGasInputController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

// controls of gas input
@property (strong, nonatomic) UILabel *yearLabel;
@property (strong, nonatomic) UILabel *monthLabel;
@property (strong, nonatomic) UILabel *dayLabel;
@property (strong, nonatomic) UITextField *odometerTextField;
@property (strong, nonatomic) UITextField *priceTextField;
@property (strong, nonatomic) UITextField *gasTextField;
@property (strong, nonatomic) UITextField *moneyTextField;
@property (strong, nonatomic) UISwitch *fillUpSwitch;

@property (strong, nonatomic) UIDatePicker *datePicker;         // datePicker of record creation date
@property (strong, nonatomic) NSIndexPath *datePickerIndexPath; // use for datePicker show up

@property (strong, nonatomic) NSMutableArray *textFields;       // text Field input objects, use for CNKeyBoardTopBar
@property (strong, nonatomic) CNKeyBoardTopBar *keyBoardTopBar; // tool bar on the top of keyboard
@property (weak, nonatomic)   UITextField *currentEditTextField;// text Field currently got the foucs

@property (strong, nonatomic) CNGasMoneyCaculator *gasMoneyCaculator; // caculate on of price/money/gas, with the other two values

@property (nonatomic) float lastPrice;                          // rememberd last price

@end

@implementation CNGasInputController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _textFields = [[NSMutableArray alloc] init];
        
        _keyBoardTopBar = [[CNKeyBoardTopBar alloc] init];
        [_keyBoardTopBar setAllowShowPreAndNext:YES];
        [_keyBoardTopBar setIsInNavigationController:NO];
        [_keyBoardTopBar setTextFieldsArray:_textFields];
        
        //register keyboard show up notification
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShownNotify:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        
        // register TextField change notification
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(textFieldChangeNotify:)
                                                     name:UITextFieldTextDidChangeNotification
                                                   object:nil];
        
        _gasMoneyCaculator = [[CNGasMoneyCaculator alloc] init];
        
        self.edittingDate = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
        self.edittingPrice = self.lastPrice;
    }
    return self;
}

- (void)dealloc
{
    // unregister all notifications
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    [self loadNavigationViews];
    
    [self.view addSubview:_keyBoardTopBar.view];
    
    [_tableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_table"]]];

    [_scrollView setContentSize:CGSizeMake(320, 600)];
    


}


- (void)loadNavigationViews
{
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"卡诺"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:nil
                                                                            action:nil];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"保养"
                                                                  style:UIBarButtonItemStylePlain
                                                                 target:self
                                                                 action:@selector(changeToServiceInput)];
    
    self.navigationItem.rightBarButtonItem = rightItem;
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];

    self.navigationItem.title = @"添加加油记录" ;
    
}


- (IBAction)saveGasInput:(id)sender
{
    self.lastPrice = [_priceTextField.text floatValue];
    
    // save inputs
    if (_datePicker) {
        self.edittingDate = _datePicker.date;
    }
    self.edittingOdomter = [_odometerTextField.text integerValue];
    self.edittingPrice = [_priceTextField.text floatValue];
    self.edittingGas = [_gasTextField.text floatValue];
    self.edittingMoney = [_moneyTextField.text floatValue];
    self.edittingIsFillUp = _fillUpSwitch.on;
    
    CNGasInfo *gasInfo = [[CNGasInfo alloc] init];
    gasInfo.createTimestamp = [self.edittingDate timeIntervalSince1970];
    gasInfo.price = self.edittingPrice;
    gasInfo.fillGas = self.edittingGas;
    gasInfo.totalPay = self.edittingMoney;
    gasInfo.isFillUp = self.edittingIsFillUp;
    gasInfo.odometer = self.edittingOdomter;
    
    if (gasInfo.totalPay <= 0) {
        return ;
    }
    
    if ([[CNGasDataManager shareInstance] saveGasInfo:gasInfo]) {
        NSLog(@"saveGasInfo success");
    }
    else {
        NSLog(@"saveGasInfo failed");
    }
    
    // exit this controller
    [self.navigationController popViewControllerAnimated:YES];
    
    // post a notification
    [[NSNotificationCenter defaultCenter] postNotificationName:kUserHasInputNewDataNotification
                                                        object:nil];
    
}

- (void)changeToServiceInput
{
    //TODO: change to service input
    
}


- (UITableViewCell *)createTimestampTableRowCell
{
    UITableViewCell * tableCell = [_tableView dequeueReusableCellWithIdentifier:kCreateTimestampCellID];
    if (tableCell == nil) {
        tableCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCreateTimestampCellID];
        [tableCell setBackgroundColor:[UIColor clearColor]];
        
        UILabel *rowTitleLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 50, 50)];
        rowTitleLable.text = @"日期";
        rowTitleLable.font = [UIFont systemFontOfSize:12.0];
        rowTitleLable.textColor = [UIColor whiteColor];
        [rowTitleLable sizeToFit];
        [tableCell.contentView addSubview:rowTitleLable];
        
        _yearLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 15, 100, 50)];
        _yearLabel.font = [UIFont systemFontOfSize:22.0];
        _yearLabel.textColor = [UIColor whiteColor];
        
        [tableCell.contentView addSubview:_yearLabel];
        
        UILabel *YEARLabel = [[UILabel alloc] initWithFrame:CGRectMake(160, 22, 50, 50)];
        YEARLabel.text = @"年";
        YEARLabel.font = [UIFont systemFontOfSize:12.0];
        YEARLabel.textColor = [UIColor whiteColor];
        [YEARLabel sizeToFit];
        [tableCell.contentView addSubview:YEARLabel];
        
        _monthLabel = [[UILabel alloc] initWithFrame:CGRectMake(185, 15, 100, 50)];
        _monthLabel.font = [UIFont systemFontOfSize:22.0];
        _monthLabel.textColor = [UIColor whiteColor];
        [tableCell.contentView addSubview:_monthLabel];
        
        UILabel *MONTHLabel = [[UILabel alloc] initWithFrame:CGRectMake(215, 22, 50, 50)];
        MONTHLabel.text = @"月";
        MONTHLabel.font = [UIFont systemFontOfSize:12.0];
        MONTHLabel.textColor = [UIColor whiteColor];
        [MONTHLabel sizeToFit];
        [tableCell.contentView addSubview:MONTHLabel];
        
        _dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(240, 15, 100, 50)];
        _dayLabel.font = [UIFont systemFontOfSize:22.0];
        _dayLabel.textColor = [UIColor whiteColor];
        
        [tableCell.contentView addSubview:_dayLabel];
        
        UILabel *DAYLabel = [[UILabel alloc] initWithFrame:CGRectMake(270, 22, 50, 50)];
        DAYLabel.text = @"日";
        DAYLabel.font = [UIFont systemFontOfSize:12.0];
        DAYLabel.textColor = [UIColor whiteColor];
        [DAYLabel sizeToFit];
        [tableCell.contentView addSubview:DAYLabel];
        
    }
    
    // load from data source
    [self updateDayLabels];
    
    return tableCell;
}

- (void)updateDayLabels
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy"];
    _yearLabel.text = [dateFormatter stringFromDate:self.edittingDate];
    [_yearLabel sizeToFit];
    
    [dateFormatter setDateFormat:@"MM"];
    _monthLabel.text = [dateFormatter stringFromDate:self.edittingDate];
    [_monthLabel sizeToFit];
    
    [dateFormatter setDateFormat:@"dd"];
    _dayLabel.text = [dateFormatter stringFromDate:self.edittingDate];
    [_dayLabel sizeToFit];
    
    
}


- (UITableViewCell *)odometerTableRowCell
{
    UITableViewCell * tableCell = [_tableView dequeueReusableCellWithIdentifier:kOdometerCellID];
    if (tableCell == nil) {
        tableCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kOdometerCellID];
        [tableCell setBackgroundColor:[UIColor clearColor]];
        
        UILabel *rowTitleLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 50, 50)];
        rowTitleLable.text = @"里程";
        rowTitleLable.font = [UIFont systemFontOfSize:12.0];
        rowTitleLable.textColor = [UIColor whiteColor];
        [rowTitleLable sizeToFit];
        [tableCell.contentView addSubview:rowTitleLable];
        
        _odometerTextField = [[UITextField alloc] initWithFrame:CGRectMake(105, 0, 100, 40)];
        _odometerTextField.text = @"0";
        _odometerTextField.textColor = [UIColor whiteColor];
        _odometerTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        _odometerTextField.font = [UIFont systemFontOfSize:22.0];
        _odometerTextField.keyboardType = UIKeyboardTypeNumberPad;
        _odometerTextField.delegate = self;
        
        [tableCell.contentView addSubview:_odometerTextField];
        
        UILabel *KMLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 22, 50, 50)];
        KMLabel.text = @"KM";
        KMLabel.font = [UIFont systemFontOfSize:12.0];
        KMLabel.textColor = [UIColor whiteColor];
        [KMLabel sizeToFit];
        [tableCell.contentView addSubview:KMLabel];
                
        [_textFields addObject:_odometerTextField];
    }
    
    // load from data source
    _odometerTextField.text = [NSString stringWithFormat:@"%d", self.edittingOdomter];
    
    return tableCell;
}


- (UITableViewCell *)priceTableRowCell
{
    UITableViewCell * tableCell = [_tableView dequeueReusableCellWithIdentifier:kPriceCellID];
    if (tableCell == nil) {
        tableCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kPriceCellID];
        [tableCell setBackgroundColor:[UIColor clearColor]];
        
        UILabel *rowTitleLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 50, 50)];
        
        rowTitleLable.text = @"单价";
        rowTitleLable.font = [UIFont systemFontOfSize:12.0];
        rowTitleLable.textColor = [UIColor whiteColor];
        [rowTitleLable sizeToFit];
        [tableCell.contentView addSubview:rowTitleLable];
        
        _priceTextField = [[UITextField alloc] initWithFrame:CGRectMake(105, 0, 100, 40)];
        _priceTextField.text = [NSString stringWithFormat:@"%0.2f", self.lastPrice];
        _priceTextField.textColor = [UIColor whiteColor];
        _priceTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        _priceTextField.font = [UIFont systemFontOfSize:22.0];
        _priceTextField.keyboardType = UIKeyboardTypeDecimalPad;
        _priceTextField.delegate = self;
        [tableCell.contentView addSubview:_priceTextField];
        
        UILabel *RMBLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 22, 50, 50)];
        RMBLabel.text = @"元/L";
        RMBLabel.font = [UIFont systemFontOfSize:12.0];
        RMBLabel.textColor = [UIColor whiteColor];
        [RMBLabel sizeToFit];
        [tableCell.contentView addSubview:RMBLabel];
        
        [_textFields addObject:_priceTextField];
        
        [_gasMoneyCaculator pushCaculateFactor:GasMoneyCaculateFactorPrice value:self.lastPrice];
    }
    
    // load from data source
    _priceTextField.text = [NSString stringWithFormat:@"%0.2f", self.edittingPrice];
    
    return tableCell;
}


- (UITableViewCell *)fillGasTableRowCell
{
    UITableViewCell * tableCell = [_tableView dequeueReusableCellWithIdentifier:kFillGasCellID];
    if (tableCell == nil) {
        tableCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kFillGasCellID];
        [tableCell setBackgroundColor:[UIColor clearColor]];
        
        UILabel *rowTitleLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 50, 50)];
        
        rowTitleLable.text = @"加油";
        rowTitleLable.font = [UIFont systemFontOfSize:12.0];
        rowTitleLable.textColor = [UIColor whiteColor];
        [rowTitleLable sizeToFit];
        [tableCell.contentView addSubview:rowTitleLable];
        
        
        _gasTextField = [[UITextField alloc] initWithFrame:CGRectMake(105, 0, 100, 40)];
        _gasTextField.text = @"0.0";
        _gasTextField.textColor = [UIColor whiteColor];
        _gasTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        _gasTextField.font = [UIFont systemFontOfSize:22.0];
        _gasTextField.keyboardType = UIKeyboardTypeDecimalPad;
        _gasTextField.delegate = self;
        [tableCell.contentView addSubview:_gasTextField];
        
        UILabel *GASLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 22, 50, 50)];
        GASLabel.text = @"L";
        GASLabel.font = [UIFont systemFontOfSize:12.0];
        GASLabel.textColor = [UIColor whiteColor];
        [GASLabel sizeToFit];
        [tableCell.contentView addSubview:GASLabel];
        
        [_textFields addObject:_gasTextField];
    }
    
    // load from data source
    _gasTextField.text = [NSString stringWithFormat:@"%0.2f", self.edittingGas];
    
    return tableCell;
}


- (UITableViewCell *)totalPayTableRowCell
{
    UITableViewCell * tableCell = [_tableView dequeueReusableCellWithIdentifier:kTotalPayCellID];
    if (tableCell == nil) {
        tableCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kTotalPayCellID];
        [tableCell setBackgroundColor:[UIColor clearColor]];
        
        UILabel *rowTitleLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 50, 50)];
        
        rowTitleLable.text = @"总价";
        rowTitleLable.font = [UIFont systemFontOfSize:12.0];
        rowTitleLable.textColor = [UIColor whiteColor];
        [rowTitleLable sizeToFit];
        [tableCell.contentView addSubview:rowTitleLable];
        
        _moneyTextField = [[UITextField alloc] initWithFrame:CGRectMake(105, 0, 100, 40)];
        _moneyTextField.text = @"0.0";
        _moneyTextField.textColor = [UIColor whiteColor];
        _moneyTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        _moneyTextField.font = [UIFont systemFontOfSize:22.0];
        _moneyTextField.keyboardType = UIKeyboardTypeDecimalPad;
        _moneyTextField.delegate = self;
        [tableCell.contentView addSubview:_moneyTextField];
        
        UILabel *RMBLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 22, 50, 50)];
        RMBLabel.text = @"元";
        RMBLabel.font = [UIFont systemFontOfSize:12.0];
        RMBLabel.textColor = [UIColor whiteColor];
        [RMBLabel sizeToFit];
        [tableCell.contentView addSubview:RMBLabel];
        
        [_textFields addObject:_moneyTextField];
    }

    // load from data source
    _moneyTextField.text = [NSString stringWithFormat:@"%0.2f", self.edittingMoney];
    
    
    return tableCell;
}


- (UITableViewCell *)isFillUpTableRowCell
{
    UITableViewCell * tableCell = [_tableView dequeueReusableCellWithIdentifier:kIsFillUpCellID];
    if (tableCell == nil) {
        tableCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kIsFillUpCellID];
        [tableCell setBackgroundColor:[UIColor clearColor]];
        
        UILabel *rowTitleLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 50, 50)];
        
        rowTitleLable.text = @"加满";
        rowTitleLable.font = [UIFont systemFontOfSize:12.0];
        rowTitleLable.textColor = [UIColor whiteColor];
        [rowTitleLable sizeToFit];
        [tableCell.contentView addSubview:rowTitleLable];
        
        _fillUpSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(105, 8, 100, 50)];
        [_fillUpSwitch setOnTintColor:[UIColor whiteColor]];
        [tableCell.contentView addSubview:_fillUpSwitch];
    }
    
    // load fromd data source
    [_fillUpSwitch setOn:self.edittingIsFillUp];
    
    return tableCell;
}


- (UITableViewCell *)datePickerTableRowCell
{
    UITableViewCell * tableCell = [_tableView dequeueReusableCellWithIdentifier:kDatePickerCellID];
    if (tableCell == nil) {
        tableCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDatePickerCellID];
        
        [tableCell setBackgroundColor:[UIColor clearColor]];
        [tableCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        //datePicker initialization
        _datePicker = [[UIDatePicker alloc] init];
        _datePicker.frame = tableCell.frame;
        _datePicker.backgroundColor = [UIColor clearColor];
        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        
        [tableCell.contentView addSubview:_datePicker];
    }
    
    // load from data source
    _datePicker.date = self.edittingDate;
    
    return tableCell;
}


- (void)keyboardWillShownNotify:(NSNotification *)notification
{
    CGRect keyboardFrame = [[notification.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    [_keyBoardTopBar setKeyboardHeight:keyboardFrame.size.height];
}


- (void)textFieldChangeNotify:(NSNotification *)noitfication
{
    UITextField *textField = noitfication.object;
    if (textField == _moneyTextField ) {
        float money = [_moneyTextField.text floatValue];
        [_gasMoneyCaculator pushCaculateFactor:GasMoneyCaculateFactorMoney value:money];
    }
    else if (textField == _gasTextField) {
        float gas = [_gasTextField.text floatValue];
        [_gasMoneyCaculator pushCaculateFactor:GasMoneyCaculateFactorGas value:gas];
    }
    else if (textField == _priceTextField) {
        float price = [_priceTextField.text floatValue];
        [_gasMoneyCaculator pushCaculateFactor:GasMoneyCaculateFactorPrice value:price];
    }
    
    if ([_gasMoneyCaculator resultType] == GasMoneyCaculateFactorGas) {
        _gasTextField.text = [NSString stringWithFormat:@"%0.2f", [_gasMoneyCaculator resultValue]];
    }
    else if ([_gasMoneyCaculator resultType] == GasMoneyCaculateFactorMoney) {
        _moneyTextField.text = [NSString stringWithFormat:@"%0.2f", [_gasMoneyCaculator resultValue]];
    }
    else if ([_gasMoneyCaculator resultType] == GasMoneyCaculateFactorPrice) {
        _priceTextField.text = [NSString stringWithFormat:@"%0.2f", [_gasMoneyCaculator resultValue]];
    }
}

// remembered last gas price, getter
- (float)lastPrice
{
    NSNumber *n = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastPrice"];
    if (n == nil) {
        return 0;
    }
    
    return [n floatValue];
}

// rememberd last gas price, setter
- (void)setLastPrice:(float)lastPrice
{
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithFloat:lastPrice] forKey:@"lastPrice"];
}


#pragma mark - ()


#pragma mark - (Table DataSource / Delegate)

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_datePickerIndexPath != nil) {
        return 7;
    }
    else {
        return 6;
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_datePickerIndexPath != nil && indexPath.row == 1) {
        return DatePickerHeight;
    }
    
    return 44;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *tableCell = nil;

    //第一行的处理
    if (indexPath.row == 0) {
        tableCell = [self createTimestampTableRowCell];
        return tableCell;
    }
    
    //第二行，需要区分有datePicker和无datePicker的情况
    if (indexPath.row == 1 && _datePickerIndexPath != nil) {
        tableCell = [self datePickerTableRowCell];
        return tableCell;
    }
    
    int otherRow = indexPath.row;
    if (_datePickerIndexPath != nil) {
        otherRow--;
    }
    
    switch (otherRow) {
        case 1:
            tableCell = [self odometerTableRowCell];
            break;
        case 2:
            tableCell = [self priceTableRowCell];
            break;
        case 3:
            tableCell = [self fillGasTableRowCell];
            break;
        case 4:
            tableCell = [self totalPayTableRowCell];
            break;
        case 5:
            tableCell = [self isFillUpTableRowCell];
            break;
        default:
            break;
    }
    
    return tableCell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    //点击第一行, open datePickerView
    if (_datePickerIndexPath == nil && indexPath.row == 0) {

        //重新计算tableView的整体高度
        CGRect tableViewFrame = tableView.frame;
        tableViewFrame.size.height += DatePickerHeight;
        _tableView.frame = tableViewFrame;
        //重新计算保存按钮的高度
        CGRect buttonFrame = _saveButton.frame;
        buttonFrame.origin.y += DatePickerHeight;
        _saveButton.frame = buttonFrame;
        
        [tableView beginUpdates];
        _datePickerIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
        [tableView insertRowsAtIndexPaths:@[_datePickerIndexPath] withRowAnimation:UITableViewRowAnimationFade];
        [tableView endUpdates];

        return ;
    }
    
    //点击第一行, close datePickerView
    if (_datePickerIndexPath != nil && indexPath.row == 0) {

        //重新计算tableView的整体高度
        CGRect tableViewFrame = tableView.frame;
        tableViewFrame.size.height -= DatePickerHeight;
        _tableView.frame = tableViewFrame;
        //重新计算保存按钮的高度
        CGRect buttonFrame = _saveButton.frame;
        buttonFrame.origin.y -= DatePickerHeight;
        _saveButton.frame = buttonFrame;

        // update editting date
        self.edittingDate = _datePicker.date;
        [self updateDayLabels];
        
        NSArray *indexPaths = @[_datePickerIndexPath];
        [tableView beginUpdates];
        [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        _datePickerIndexPath = nil;
        [tableView endUpdates];
        
        return ;
    }
    
    //datePicker存在时，点击第二行的处理
    if (_datePickerIndexPath != nil && _datePickerIndexPath == indexPath) {
        //tap datePikerView, do nothing
        return ;
    }

    
    //其他行的处理
    int otherRow = indexPath.row;
    if (_datePickerIndexPath != nil) {
        otherRow--;
    }
    
    [_currentEditTextField resignFirstResponder];
    switch (otherRow) {
        case 1:
            [_odometerTextField becomeFirstResponder];
            break;
        case 2:
            [_priceTextField becomeFirstResponder];
            break;
        case 3:
            [_gasTextField becomeFirstResponder];
            break;
        case 4:
            [_moneyTextField becomeFirstResponder];
            break;
        case 5:
            [_fillUpSwitch setOn:!_fillUpSwitch.on animated:YES];
            [_keyBoardTopBar hiddenKeyBoard];
            break;
        default:
            break;
    }
    
}


#pragma mark - TextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if ([textField.text floatValue] <= 0) {
        textField.text = @"";
    }
    _currentEditTextField = textField;
    [_keyBoardTopBar showBar:textField];
    
    if (textField.frame.origin.y > _keyBoardTopBar.view.frame.origin.y) {
        
        _scrollView.contentOffset = CGPointMake(0, _scrollView.contentOffset.y - (textField.frame.origin.y - _keyBoardTopBar.view.frame.origin.y) - textField.frame.size.height);
    }

}


@end
